package com.cloudbroker.bcs.platform.ltb.middle.bizservice.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.configure.ConfigUtil;
import com.cloudbroker.bcs.common.constants.BasicErrorCodes;
import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.util.EnumUtil;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.*;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.base.HeaderForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.baseRelevanted.AuthuserRegbindForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.baseRelevanted.ModAliasForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.fansRelated.InterestDetailForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.ifs.*;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.interestRelated.ComadviserBuildForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.*;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.IFS.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.type.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.admin.back.UserEntityVO;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.base.vo.BrokerVO;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.base.vo.UserVO;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.customer.back.CustomerBackVo;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.leader.back.LeaderInfoVo;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.push.vo.RegisterForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.user.UserBizService;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.user.back.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.user.back.UserLoginBack;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.user.vo.*;
import com.cloudbroker.bcs.platform.ltb.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.ltb.middle.constants.ClientMsgType;
import com.cloudbroker.bcs.platform.ltb.middle.entity.*;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.lightinvesting.LightinvestingService;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.sms.SMSExtService;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.usercenter.UserCenterService;
import com.cloudbroker.bcs.platform.ltb.middle.model.UserCache;
import com.cloudbroker.bcs.platform.ltb.middle.service.*;
import com.cloudbroker.bcs.platform.ltb.middle.util.*;
import com.cloudbroker.bcs.platform.ltb.middle.util.ssl.SSLHttpUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.Base64Utils;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.*;

import static com.cloudbroker.bcs.common.constants.BasicErrorCodes.LOGIN_AUTHORIZATION_SIGN_EORR;
import static com.cloudbroker.bcs.common.constants.BasicErrorCodes.NOT_LOGGED;
import static com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSErrorCodes.ClientErr.*;
import static com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSErrorCodes.CommonErr.*;

/**
 * Created by tianrui on 2016/7/8.
 */

@Service
public class UserBizServiceImpl implements UserBizService {

    //跟投用户信息表操作
    @Resource
    private CustomerService customerService;

    //验证码短信发送
    @Resource
    private SMSExtService smsExtService;

    //验证码存入缓存
    @Resource
    private ValidateCodeService validateCodeService;

    //用户登录表操作
    @Resource
    private UserService userService;

    //投顾信息表操作
    @Resource
    private LeaderService leaderService;

    //后台接口调用
    @Resource
    private LightinvestingService lightinvestingService;

    //第三方授权登录
    @Resource
    private LoginAuthorizationService loginAuthorizationService;

    //短信模板
    @Resource
    private ClientMsgService clientMsgService;

    @Resource
    private PushService pushService;

    @Resource
    private LoginRecordService loginRecordService;

    @Resource
    private SmsAuthkeyService smsAuthkeyService;

    @Resource
    private UserCenterService userCenterService;

    @Resource
    private OrganizationService organizationService;




    /**
     * 短信验证码发送
     * */
    @Override
    public SendSMSBack funcSendSMS(SendSMSForm form) {
        String mobile_tel = form.getMobile_tel();
        String company_id = form.getCompany_id();
        String sendercomp_id = form.getSendercomp_id();
        String verify_code ="";
        //密码重置时 需判断手机号是否已注册
        if (form.getAuthmsg_busi_type().intValue() == VerifySource.RESET_PASSWORD.getVal()){
            //投顾端投顾重置密码时 需要充数据库表中获取company_id
            if (form.getUser_type().equals(String.valueOf(UserType.LEADER.getVal()))){
                UserEntity tmp_user_entity = new UserEntity();
                tmp_user_entity.setUser_name(form.getMobile_tel());
                tmp_user_entity.setUser_type(String.valueOf(UserType.LEADER.getVal()));
                UserEntity leader_user = userService.getUserEntity(tmp_user_entity);
                company_id = leader_user.getCompany_id();
                sendercomp_id = leader_user.getSendercomp_id();
                form.setCompany_id(company_id);
                form.setSendercomp_id(sendercomp_id);
            }

            CheckRegisterForm checkRegisterForm = new CheckRegisterForm();
            checkRegisterForm.setTenant_id(form.getCompany_id());
            checkRegisterForm.setUser_type("3");
            if(form.getUser_type().equals("100")){
                checkRegisterForm.setUser_type("3");
            }else if(form.getUser_type().equals("101")){
                checkRegisterForm.setUser_type("2");
            }
            checkRegisterForm.setLogin_account(mobile_tel);
            CheckRegisterVo checkRegisterVo = userCenterService.func_check_register(checkRegisterForm);
            if(!"0".equals(checkRegisterVo.getError_no())){
                return VOUtil.genErrorResult(checkRegisterVo.getError_no(),checkRegisterVo.getError_info(), SendSMSBack.class);
            }
            if(!"1".equals(checkRegisterVo.getIs_register())){
                return VOUtil.genErrorResult(MOBILE_TEL_NOT_REGISTER, SendSMSBack.class);
            }
            AuthCodeGetForm authCodeGetForm= new AuthCodeGetForm();
            authCodeGetForm.setLogin_account(mobile_tel);
            if(form.getUser_type().equals("100")){
                authCodeGetForm.setUser_type("3");
            }else if(form.getUser_type().equals("101")){
                authCodeGetForm.setUser_type("2");
            }
            authCodeGetForm.setTenant_id(company_id);
            AuthCodeGetVo userT2AuthcodeBack =userCenterService.func_auth_code_get(authCodeGetForm);
            if(!"0".equals(userT2AuthcodeBack.getError_no())) {
                return VOUtil.genErrorResult(userT2AuthcodeBack.getError_no(),userT2AuthcodeBack.getError_info(),SendSMSBack.class);
            }
            verify_code = userT2AuthcodeBack.getAuth_code();
        }else{
            verify_code = VerifyCodeTokenUtil.getVerifyCode();
        }
        String verify_key = mobile_tel + company_id + sendercomp_id;
        VerifySource verify_source = EnumUtil.valOf(form.getAuthmsg_busi_type(), VerifySource.class);
        String verify_token = VerifyCodeTokenUtil.getVerifyCodeToken(verify_key, verify_source);
        SendSMSBack backForm = new SendSMSBack();
        boolean refresh = false;
        if (VerifyCodeTokenUtil.isExist(verify_token)){
            if (VerifyCodeTokenUtil.isRetry(verify_token)){
                refresh = true;
            }
            else{
                backForm.setCount_down(VerifyCodeTokenUtil.getCountDown(verify_token));
                backForm.setError_no(HSBCPSErrorCodes.CommonErr.SEND_MESSAGE_FREQUENTLY);
                return backForm;

            }
        }
        if (VerifyCodeTokenUtil.isDayOu(verify_token)){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.CommonErr.SEND_MESSAGE_TO_MAX, SendSMSBack.class);
        }


        if (refresh){
            verify_code = VerifyCodeTokenUtil.update(verify_code,verify_token);
        }
        else{
            verify_code = VerifyCodeTokenUtil.add(verify_code,verify_token);
        }
        //
        SmsAuthkey smsAuthkey=  smsAuthkeyService.findByType(new SmsAuthkey(101,form.getCompany_id()));
        //获取配置文件中验证码前缀
        ClientMsg clientMsg = clientMsgService.findByType(new ClientMsg(ClientMsgType.REGISTER));
        String verifyMsgContent= ClientMsgUtil.replace(clientMsg.getMsg_content(),verify_code);
//        String verifyMsgContent = ConfigValues.ClientMessage.getSendLoginVerifyCodeMessage(verify_code);
//        String verifyMsgContent = verify_code;
        //发送短信
        SendMsgForm sendMsgForm = new SendMsgForm();
        sendMsgForm.setBusinsys_no(Long.valueOf(1001));
        sendMsgForm.setMobile_tel(form.getMobile_tel());
        sendMsgForm.setSms_content(verifyMsgContent);
        sendMsgForm.setSendercomp_id(form.getSendercomp_id());
        sendMsgForm.setSms_authkey(smsAuthkey.getAuthkey());
        sendMsgForm.setCompany_id(form.getCompany_id());
        sendMsgForm.setOwn_company_id(form.getCompany_id());
        //后台需新增临时token
        String user_token = UserTokenUtil.addSMSUserToken(company_id, sendercomp_id);
        sendMsgForm.setUser_token(user_token);
        SendMsgVo sendMsgVo = lightinvestingService.func_send_message(sendMsgForm);
        if (!sendMsgVo.getError_no().equals("0")) {
            UserTokenUtil.deleteUserToken(verify_token);
            UserTokenUtil.deleteUserToken(user_token);
            return VOUtil.genBGErrorResult(sendMsgVo.getError_no(), sendMsgVo.getError_info(),  SendSMSBack.class);
        }
        UserTokenUtil.deleteUserToken(user_token);
        //短信落地
        ValidateCode validateCode = new ValidateCode();
        validateCode.setCompany_id(form.getCompany_id());
        validateCode.setCreate_time(System.currentTimeMillis());
        validateCode.setMobile(mobile_tel);
        validateCode.setValidate_content(verifyMsgContent);
        validateCodeService.addValidateCode(validateCode);
        backForm.setCount_down(ConfigValues.getSmsSendCountDown());
        return VOUtil.setSuccessResult(backForm);
    }


    /**
     * 用户登录
     * */
    @Override
    @Transactional
    public UserLoginBack funcUserLogin(UserLoginForm form) {
        //登录安全验证
        String safeKey = form.getCompany_id() + form.getSendercomp_id() + form.getLogin_account() + form.getUser_type();
        if (UserTokenUtil.updatedLoginUserToken(safeKey)){
            return VOUtil.genErrorResult(BALEFUL_USER_LOGIN, UserLoginBack.class);
        }
        String login_away = form.getLogin_way();
        if (!login_away.equals(String.valueOf(LoginAwayType.MOBILE.getVal()))){
            return VOUtil.genErrorResult(USER_LOGIN_AWAY_ERROE, UserLoginBack.class);
        }
        UserType user_type = EnumUtil.valOf(Integer.valueOf(form.getUser_type()), UserType.class);

        //用户中心登录
        LoginForm userT2LoginForm = new LoginForm();
        userT2LoginForm.setLogin_account(form.getLogin_account());
        userT2LoginForm.setAuth_password(MD5Util.encrypt(form.getPassword()));
        if(form.getUser_type().equals("100")){
            userT2LoginForm.setUser_type("3");
        }else if(form.getUser_type().equals("101")){
            userT2LoginForm.setUser_type("2");
        }
        userT2LoginForm.setTenant_id(form.getCompany_id());
        LoginVo userT2LoginBack = userCenterService.func_login(userT2LoginForm);
        if(!"0".equals(userT2LoginBack.getError_no())) {
            return VOUtil.genErrorResult(userT2LoginBack.getError_no(),userT2LoginBack.getError_info(),UserLoginBack.class);
        }
        UserinfoForm userinfoForm = new UserinfoForm();
        userinfoForm.setUser_token(userT2LoginBack.getUser_token());
        UserinfoVo userT2InfoBack = userCenterService.func_userinfo(userinfoForm);
        if(!"0".equals(userT2InfoBack.getError_no())) {
            return VOUtil.genErrorResult(userT2InfoBack.getError_no(),userT2InfoBack.getError_info(),UserLoginBack.class);
        }
        UserEntity verifyUser = userService.get(userT2InfoBack.getUser_id()+"");

        if(verifyUser == null){
            verifyUser=new UserEntity();
            AdviserGetVo adviserGetVo=null;
            if("2".equals(userT2InfoBack.getUser_type())){
                AdviserGetForm adviserGetForm = new AdviserGetForm();
                adviserGetForm.setUser_id(userT2InfoBack.getUser_id());
                adviserGetForm.setUser_token(userT2LoginBack.getUser_token());
                adviserGetVo = userCenterService.func_adviser_get(adviserGetForm);
                if(!"0".equals(adviserGetVo.getError_no())) {
                    return VOUtil.genErrorResult(adviserGetVo.getError_no(),adviserGetVo.getError_info(),UserLoginBack.class);
                }
                Leader leader = new Leader(adviserGetVo.getAlias_name(), adviserGetVo.getMobile(),
                        System.currentTimeMillis(), adviserGetVo.getTenant_id());
                leader.setJob_state(LeaderJobStateType.ON.getVal());
//                leader.setJob_title(adviserGetVo.getJob_title());
//                leader.setSex(adviserGetVo.get);
                leader.setQq(adviserGetVo.getQq_no());
//                leader.setProfile(form.getBackground_info());
                leader.setId_no(adviserGetVo.getId_card_no());
//                leader.setCertificate_id(form.getQualify_no());
                leaderService.addLeader(leader);
                verifyUser.setInvite_code(adviserGetVo.getReferral_code());
                verifyUser.setAccounts_id(leader.getLeader_id());
                verifyUser.setUser_type(String.valueOf(UserType.LEADER.getVal()));
            }else {
                Customer new_customer =new Customer(form.getLogin_account(),form.getLogin_account(),
                        System.currentTimeMillis(), form.getCompany_id());
                customerService.addCustomer(new_customer);
                verifyUser.setAccounts_id(new_customer.getCustomer_id());
                verifyUser.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
            }
            verifyUser.setUser_id(Long.parseLong(userT2InfoBack.getUser_id()));
            verifyUser.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
            verifyUser.setCompany_id(userT2InfoBack.getTenant_id());
            verifyUser.setSendercomp_id(userT2InfoBack.getTenant_id());
            verifyUser.setUser_name(userT2InfoBack.getLogin_account());
            verifyUser.setUser_status(userT2InfoBack.getUser_status());
            verifyUser.setAlias_name(userT2InfoBack.getAlias_name());
            verifyUser.setAvatar(userT2InfoBack.getAvatar());
            verifyUser.setMobile(userT2InfoBack.getMobile());
            userService.addUser(verifyUser);
//            regForm.setUser_token(user_token);
            if("2".equals(userT2InfoBack.getUser_type())){
                ComadviserBuildForm comadviserBuildForm = new ComadviserBuildForm();
                comadviserBuildForm.setNeed_user_id("1");
                comadviserBuildForm.setMobile_tel(adviserGetVo.getMobile());
                comadviserBuildForm.setNeed_user_id("1");
                comadviserBuildForm.setAdviser_id(userT2InfoBack.getUser_id());
                comadviserBuildForm.setUser_id(userT2InfoBack.getUser_id());
                comadviserBuildForm.setClient_name(adviserGetVo.getApplicant_name());
                comadviserBuildForm.setAdviser_type(adviserGetVo.getAdviser_type());
                comadviserBuildForm.setBackground_info(adviserGetVo.getBackground_intro());
                String op_branch_no = organizationService.getOp_Branch_No(userT2InfoBack.getTenant_id());
                comadviserBuildForm.setOp_branch_no(Integer.parseInt(op_branch_no));
                comadviserBuildForm.setOp_entrust_way("7");
                comadviserBuildForm.setOp_station(adviserGetVo.getBusiness_dept());
                comadviserBuildForm.setOp_password(adviserGetVo.getAuth_password());
                comadviserBuildForm.setSendercomp_id(adviserGetVo.getTenant_id());
                comadviserBuildForm.setPromotion_flag("0");
                comadviserBuildForm.setCompany_id(adviserGetVo.getTenant_id());
                comadviserBuildForm.setId_kind("0");
                comadviserBuildForm.setId_no(adviserGetVo.getId_card_no());
                comadviserBuildForm.setQualify_no(adviserGetVo.getCredentials_no());
                if(StringUtils.isBlank(adviserGetVo.getBranch_no())){
                    adviserGetVo.setBranch_no("0");
                }
                comadviserBuildForm.setClient_branch_no(Long.parseLong(adviserGetVo.getBranch_no()));
                HeaderForm headerForm = new HeaderForm();
                headerForm.setCompany_id(userT2InfoBack.getTenant_id());
                headerForm.setSendercomp_id(userT2InfoBack.getTenant_id());
                comadviserBuildForm.setHeaderForm(headerForm);
                ComadviserBuildVo comadviserBuildVo= lightinvestingService.func_comadviser_build(comadviserBuildForm);
                if (comadviserBuildVo.getSerial_no() == null) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return VOUtil.genErrorResult(comadviserBuildVo.getError_no(), comadviserBuildVo.getError_info(), UserLoginBack.class);
                }
            }else {
                RegForm regForm = new RegForm();
                regForm.setAlias_name(form.getLogin_account());
                regForm.setMobile_tel(form.getLogin_account());
                regForm.setNeed_user_id("1");
                regForm.setUser_id(String.valueOf(verifyUser.getUser_id()));
                regForm.setSendercomp_id(form.getSendercomp_id());
                HeaderForm headerForm = new HeaderForm();
                headerForm.setCompany_id(form.getCompany_id());
                headerForm.setSendercomp_id(form.getSendercomp_id());
                regForm.setHeaderForm(headerForm);
                RegBackVo backVo = lightinvestingService.func_register_authuser(regForm);
                if (backVo.getSerial_no() == null) {
//                throw new RuntimeException(backVo.getError_no() + "|" + backVo.getError_info());
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return VOUtil.genErrorResult(backVo.getError_no(), backVo.getError_info(), UserLoginBack.class);

                }
            }
        }else{
            verifyUser.setAlias_name(userT2InfoBack.getAlias_name());
            verifyUser.setAvatar(userT2InfoBack.getAvatar());
            verifyUser.setUser_status(userT2InfoBack.getUser_status());
            userService.update(verifyUser);
            if(verifyUser.getUser_type().equals(String.valueOf(UserType.LEADER.getVal()))){
                Leader temp = new Leader();
                temp.setLeader_id(verifyUser.getAccounts_id());
                Leader leader = leaderService.getLeader(temp);
                if(leader.getJob_state().equals(LeaderJobStateType.OFF.getVal())){
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.LEADER_LEAVE,UserLoginBack.class);
                }
            }
            if("3".equals(userT2InfoBack.getUser_type())) {//粉丝修改后台昵称
                ModAliasForm modAliasForm = new ModAliasForm();
                modAliasForm.setAlias_name(userT2InfoBack.getAlias_name());
                modAliasForm.setUser_id(String.valueOf(userT2InfoBack.getUser_id()));
                modAliasForm.setSendercomp_id(userT2InfoBack.getTenant_id());
                modAliasForm.setUser_token(userT2LoginBack.getUser_token());
                modAliasForm.setNeed_user_id("1");
                HeaderForm headerForm = new HeaderForm();
                headerForm.setCompany_id(userT2InfoBack.getTenant_id());
                headerForm.setSendercomp_id(userT2InfoBack.getTenant_id());
                modAliasForm.setHeaderForm(headerForm);
                ModAliasVo modAliasVo = null;
                try {
                    modAliasVo = lightinvestingService.func_alias_mod(modAliasForm);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        long last_login_time = verifyUser.getLast_login_time();
        //校验用户状态是否为正常
        if (!String.valueOf(UserStatus.NORMAL.getVal()).equals(verifyUser.getUser_status())){
            //若是投顾用户 需调用后台接口进行判断
            if (user_type == UserType.LEADER){
                //密码校验成功赋值company_id和sendercomp_id
                form.setCompany_id(verifyUser.getCompany_id());
                form.setSendercomp_id(verifyUser.getSendercomp_id());
                InterestDetailVo interestDetailVo = leaderIsPassed(form, verifyUser.getUser_id());
               if (interestDetailVo == null){
                    return VOUtil.genErrorResult(LEADER_STATUS_WAITING, UserLoginBack.class);
               }else {
                    //投顾验证通过更新中台数据库
                   UserEntity userEntity = new UserEntity();
                   userEntity.setUser_id(verifyUser.getUser_id());
                   userEntity.setUser_status(String.valueOf(UserStatus.NORMAL.getVal()));
                   userService.updateUserStatus(userEntity);
               }
            }else {
                return VOUtil.genErrorResult(USER_STATUS_DISABLE, UserLoginBack.class);
            }
        }
        //保存登录时间
        UserEntity userEntity = new UserEntity();
        userEntity.setUser_id(verifyUser.getUser_id());
        userEntity.setLast_login_time(System.currentTimeMillis());
        userService.updateUserLoginTime(userEntity);
        //保存登录记录
        LoginRecord loginRecord = new LoginRecord();
        loginRecord.setCompany_id(verifyUser.getCompany_id());
        loginRecord.setLogin_time(System.currentTimeMillis());
        loginRecord.setUser_id(verifyUser.getUser_id());
        loginRecord.setLogin_ip(form.getIp());
        loginRecordService.save(loginRecord);
        //登录成功拼装缓存数据 删除游客token
        UserTokenUtil.deleteUserToken(form.getUser_token());
        UserCache userCache = new UserCache();
        //后台数据缓存
        BrokerVO brokerVO = new BrokerVO();
        UserTokenUtil.setBGBrokerVO(brokerVO, form);
        brokerVO.setCompany_id(verifyUser.getCompany_id());
        brokerVO.setSendercomp_id(verifyUser.getSendercomp_id());
        brokerVO.setLast_login_time(last_login_time);
        userCache.setBrokerVO(brokerVO);
        userCache.setAccess_token(userT2LoginBack.getUser_token());
        switch (user_type){
            case CUSTOMER:{
                Customer customer = customerService.getCustomer(new Customer(verifyUser.getAccounts_id()));
                if (null != customer) {
                    CustomerBackVo customerBackVo = JSON.parseObject(JSON.toJSONString(customer),CustomerBackVo.class);
                    initParentField(customerBackVo, verifyUser);
                    customerBackVo.setAlias_name(userT2InfoBack.getAlias_name());
                    customerBackVo.setAvatar(userT2InfoBack.getAvatar());
                    customerBackVo.setCity_name(userT2InfoBack.getCity_name());
                    customerBackVo.setProvince_name(userT2InfoBack.getProvince_name());
                    userCache.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
                    customerBackVo.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
                    customerBackVo.setUser_key(verifyUser.getUser_key());
                    userCache.getBrokerVO().setUser(customerBackVo);
                }else {
                    return VOUtil.genErrorResult(CUSTOMER_INFO_NOT_EXIST, UserLoginBack.class);
                }
            }
                break;
            case LEADER:{
                Leader leader = leaderService.getLeader(new Leader(verifyUser.getAccounts_id()));
                if (null != leader) {
                    LeaderInfoVo leaderInfoVo =JSON.parseObject(JSON.toJSONString(leader),LeaderInfoVo.class);
                    initParentField(leaderInfoVo, verifyUser);
                    leaderInfoVo.setAlias_name(userT2InfoBack.getAlias_name());
                    leaderInfoVo.setAvatar(userT2InfoBack.getAvatar());
                    leaderInfoVo.setCity_name(userT2InfoBack.getCity_name());
                    leaderInfoVo.setProvince_name(userT2InfoBack.getProvince_name());
                    userCache.setUser_type(String.valueOf(UserType.LEADER.getVal()));
                    leaderInfoVo.setUser_type(String.valueOf(UserType.LEADER.getVal()));
                    leaderInfoVo.setUser_key(verifyUser.getUser_key());
                    userCache.getBrokerVO().setUser(leaderInfoVo);
                }else {
                    return VOUtil.genErrorResult(LEADER_INFO_NOT_EXIST, UserLoginBack.class);
                }
            }
                break;
            case ADMIN:
                break;
            default:
                break;
        }
        String user_token = UserTokenUtil.addUserToken(userCache);
//        //设置推送别名
//        pushService.setAliasName(userCache.getBrokerVO().getUser().getUser_id(),userCache.getBrokerVO().getCompany_id(),userCache.getBrokerVO().getSendercomp_id());
        //保存极光推送信息
        if(!StringUtil.isEmpty(form.getRegistration_id())) {
            RegisterForm regForm = new RegisterForm();
            regForm.setRegistration_id(form.getRegistration_id());
            UserVO userVO = new UserVO();
            userVO.setUser_id(verifyUser.getUser_id());
            regForm.setUser(userVO);
            regForm.setCompany_id(form.getCompany_id());
            regForm.setSendercomp_id(form.getCompany_id());
            regForm.setTerminal_type(form.getTerminal_type());
            regForm.setAlias_name(String.valueOf(userCache.getBrokerVO().getUser().getUser_id()));
            try{
                pushService.registrationIdMgr(regForm);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        UserLoginBack userLoginBack = new UserLoginBack();
        userLoginBack.setUser_token(user_token);
        userLoginBack.setAlias(userCache.getBrokerVO().getUser().getUser_id());
        userLoginBack.setCompany_id(userT2InfoBack.getTenant_id());
        return VOUtil.setSuccessResult(userLoginBack);
    }



    @Override
    @Transactional
    public UserLoginBack loginAuthorization(LoginAuthorizationForm form) {

        String ltb_key = loginAuthorizationService.getLtbKey(form.getLtb_uid());
        String login_away = form.getLogin_way();
        if (!login_away.equals(String.valueOf(LoginAwayType.AUTHORIZATION.getVal()))){
            return VOUtil.genErrorResult(USER_LOGIN_AWAY_ERROE, UserLoginBack.class);
        }
        String user_name = form.getLogin_account();
        TreeMap<String, String> paramsMap = new TreeMap<String, String>();
        paramsMap.put("company_id", form.getCompany_id());
        paramsMap.put("sendercomp_id", form.getSendercomp_id());
        if(form.getOp_branch_no()!=0) {
            paramsMap.put("op_branch_no", form.getOp_branch_no() + "");
        }
        if(form.getBranch_no()!=0) {
            paramsMap.put("branch_no", form.getBranch_no() + "");
        }
        paramsMap.put("op_entrust_way",form.getOp_entrust_way());
        paramsMap.put("op_station",form.getOp_station());
        paramsMap.put("login_account", form.getLogin_account());
        paramsMap.put("login_way", form.getLogin_way());
        paramsMap.put("user_type", form.getUser_type());
        paramsMap.put("timestamp", form.getTimestamp());
        paramsMap.put("ltb_uid", form.getLtb_uid());
        String params = MD5Util.dictSort(paramsMap);
        if (!form.getSign().equalsIgnoreCase(MD5Util.encrypt(params+ltb_key)))
            return VOUtil.genErrorResult(LOGIN_AUTHORIZATION_SIGN_EORR, UserLoginBack.class);
        if (form.getUser_token().equals("")) {
            return VOUtil.genErrorResult(NOT_LOGGED, UserLoginBack.class);
        }
        UserEntity verifyUser = userService.userLoginVerify(new UserEntity(user_name,
                form.getUser_type(), form.getSendercomp_id(), form.getCompany_id()));
        //校验用户,如果不存在则注册
        if(null == verifyUser ){
            String mobile_tel = form.getLogin_account();
            String sendercomp_id = form.getSendercomp_id();
            String user_type = String.valueOf(UserType.CUSTOMER.getVal());
            String alias_name = mobile_tel;
            String company_id = form.getCompany_id();
            Customer new_customer =new Customer(alias_name,mobile_tel,
                    System.currentTimeMillis(), company_id);
            customerService.addCustomer(new_customer);
            //注册到ITN
            AuthuserRegbindForm authuserRegbindForm = new AuthuserRegbindForm();
            authuserRegbindForm.setBusinsys_no(Long.valueOf(1001));
            authuserRegbindForm.setSendercomp_id(form.getSendercomp_id());
            authuserRegbindForm.setMobile_tel(form.getLogin_account());
            authuserRegbindForm.setUser_token(form.getUser_token());
            AuthuserRegbindVo authuserRegbindVo = new AuthuserRegbindVo();
            try {
                authuserRegbindVo = lightinvestingService.func_authuser_regbind(authuserRegbindForm);
            }catch (Exception e){
                //成功与否不要影响注册流程
                e.printStackTrace();
            }
            if (authuserRegbindVo == null || authuserRegbindVo.getUser_id() == null){
                authuserRegbindVo.setUser_id("0");
            }
            //刷新user信息
            long customer_id = new_customer.getCustomer_id();
            //更新user表
            String user_key = String.valueOf(System.nanoTime());
            UserEntity userEntity = new UserEntity();
            userEntity.setCompany_id(form.getCompany_id());
            userEntity.setSendercomp_id(form.getSendercomp_id());
            userEntity.setPassword(MD5Util.encrypt(form.getPassword()));
            userEntity.setUser_name(mobile_tel);
            userEntity.setAccounts_id(customer_id);
            userEntity.setUser_key(user_key);
            userEntity.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
            userEntity.setMobile(mobile_tel);
            userEntity.setAlias_name(mobile_tel);
            userEntity.setUser_status(String.valueOf(UserStatus.NORMAL.getVal()));
//        userEntity.setCif_id(Long.valueOf(authuserRegbindVo.getAuth_id()));
            userService.addUser(userEntity);
            //customer数据组装
            UserEntity bgUser = userService.getUserEntity(userEntity);
            UserBizServiceImpl userBizService = new UserBizServiceImpl();
            UserCache userCache = new UserCache();
            BrokerVO brokerVO = new BrokerVO();
            CustomerBackVo customerBackVo = new CustomerBackVo();
            customerBackVo.setCustomer_id(bgUser.getAccounts_id());
            userBizService.initParentField(customerBackVo, bgUser);
            brokerVO.setUser(customerBackVo);
            form.setUser_key(String.valueOf(bgUser.getUser_id()));
            UserTokenUtil.setBGBrokerVO(brokerVO, form);
            userCache.setBrokerVO(brokerVO);
            UserLoginBack userLoginBack = new UserLoginBack();
            String user_token = UserTokenUtil.addUserToken(userCache);
            //本地注册成功后发送数据到后台注册
            RegForm regForm = new RegForm();
            regForm.setAlias_name(alias_name);
            regForm.setMobile_tel(form.getLogin_account());
            regForm.setNeed_user_id("1");
            regForm.setUser_id(String.valueOf(bgUser.getUser_id()));
            regForm.setSendercomp_id(form.getSendercomp_id());
            regForm.setUser_token(user_token);
            RegBackVo backVo = lightinvestingService.func_register_authuser(regForm);
            if (backVo.getSerial_no() == null){
                UserTokenUtil.deleteUserToken(user_token);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return VOUtil.genErrorResult(backVo.getError_no(),backVo.getError_info(),UserLoginBack.class);
//                throw new RuntimeException(backVo.getError_no() + "|" + backVo.getError_info());
            }
            userLoginBack.setUser_token(user_token);
            //删除游客token
            UserTokenUtil.deleteUserToken(form.getUser_token());
            return VOUtil.setSuccessResult(userLoginBack);
        }
        //校验用户状态是否为正常
        if (!verifyUser.getUser_status().equals(String.valueOf(UserStatus.NORMAL.getVal()))){
                return VOUtil.genErrorResult(USER_STATUS_DISABLE, UserLoginBack.class);
        }
        //登录成功拼装缓存数据 删除游客token
        UserTokenUtil.deleteUserToken(form.getUser_token());
        UserCache userCache = new UserCache();
        //后台数据缓存
        BrokerVO brokerVO = new BrokerVO();
        UserTokenUtil.setBGBrokerVO(brokerVO, form);
        brokerVO.setCompany_id(verifyUser.getCompany_id());
        brokerVO.setSendercomp_id(verifyUser.getSendercomp_id());
        userCache.setBrokerVO(brokerVO);
        Customer customer = customerService.getCustomer(new Customer(verifyUser.getAccounts_id()));
        if ( customer !=null) {
            CustomerBackVo customerBackVo = JSON.parseObject(JSON.toJSONString(customer),CustomerBackVo.class);
            initParentField(customerBackVo, verifyUser);
            userCache.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
            customerBackVo.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
            customerBackVo.setUser_key(verifyUser.getUser_key());
            userCache.getBrokerVO().setUser(customerBackVo);
        }else {
            return VOUtil.genErrorResult(CUSTOMER_INFO_NOT_EXIST, UserLoginBack.class);
        }
        String user_token = UserTokenUtil.addUserToken(userCache);
        UserLoginBack userLoginBack = new UserLoginBack();
        userLoginBack.setUser_token(user_token);
        userLoginBack.setCompany_id(verifyUser.getCompany_id());
        return VOUtil.setSuccessResult(userLoginBack);
    }

    @Transactional
    public UserLoginBack redirectLogin(RedirectLoginForm form){
        UserinfoForm userinfoForm = new UserinfoForm();
        userinfoForm.setUser_token(form.getAuthorization_token());
        UserinfoVo userT2InfoBack = userCenterService.func_userinfo(userinfoForm);
        if(!"0".equals(userT2InfoBack.getError_no())) {
            return VOUtil.genErrorResult(userT2InfoBack.getError_no(),userT2InfoBack.getError_info(),UserLoginBack.class);
        }
        UserEntity verifyUser = userService.get(userT2InfoBack.getUser_id()+"");

        if(verifyUser == null){
            if("2".equals(userT2InfoBack.getUser_type())){
                return VOUtil.genErrorResult(CLIENT_NAME_ERR, UserLoginBack.class);
            }
            Customer new_customer =new Customer(userT2InfoBack.getAlias_name(),userT2InfoBack.getLogin_account(),
                    System.currentTimeMillis(), userT2InfoBack.getTenant_id());
            customerService.addCustomer(new_customer);
            verifyUser = new UserEntity();
            verifyUser.setUser_id(Long.parseLong(userT2InfoBack.getUser_id()));
            verifyUser.setAccounts_id(new_customer.getCustomer_id());
            verifyUser.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
            verifyUser.setCompany_id(userT2InfoBack.getTenant_id());
            verifyUser.setSendercomp_id(userT2InfoBack.getTenant_id());
            verifyUser.setUser_name(userT2InfoBack.getLogin_account());
            verifyUser.setUser_status(userT2InfoBack.getUser_status());
            verifyUser.setAlias_name(userT2InfoBack.getAlias_name());
            verifyUser.setAvatar(userT2InfoBack.getAvatar());
            verifyUser.setMobile(userT2InfoBack.getMobile());
            userService.addUser(verifyUser);
            RegForm regForm = new RegForm();
            regForm.setAlias_name(userT2InfoBack.getAlias_name());
            regForm.setMobile_tel(userT2InfoBack.getLogin_account());
            regForm.setNeed_user_id("1");
            regForm.setUser_id(String.valueOf(verifyUser.getUser_id()));
            regForm.setSendercomp_id(userT2InfoBack.getTenant_id());
            HeaderForm headerForm = new HeaderForm();
            headerForm.setCompany_id(form.getCompany_id());
            headerForm.setSendercomp_id(form.getSendercomp_id());
            regForm.setHeaderForm(headerForm);
            RegBackVo backVo = lightinvestingService.func_register_authuser(regForm);
            if (backVo.getSerial_no() == null){
//                throw new RuntimeException(backVo.getError_no() + "|" + backVo.getError_info());
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return VOUtil.genErrorResult(backVo.getError_no(),backVo.getError_info(),UserLoginBack.class);
            }
        }else{
            verifyUser.setAlias_name(userT2InfoBack.getAlias_name());
            verifyUser.setAvatar(userT2InfoBack.getAvatar());
            verifyUser.setUser_status(userT2InfoBack.getUser_status());
            userService.update(verifyUser);
            if("3".equals(userT2InfoBack.getUser_type())) {//粉丝修改后台昵称
                ModAliasForm modAliasForm = new ModAliasForm();
                modAliasForm.setAlias_name(userT2InfoBack.getAlias_name());
                modAliasForm.setUser_id(String.valueOf(userT2InfoBack.getUser_id()));
                modAliasForm.setSendercomp_id(userT2InfoBack.getTenant_id());
//                modAliasForm.setUser_token(userT2LoginBack.getUser_token());
                modAliasForm.setNeed_user_id("1");
                HeaderForm headerForm = new HeaderForm();
                headerForm.setCompany_id(userT2InfoBack.getTenant_id());
                headerForm.setSendercomp_id(userT2InfoBack.getTenant_id());
                modAliasForm.setHeaderForm(headerForm);
                ModAliasVo modAliasVo = null;
                try {
                    modAliasVo = lightinvestingService.func_alias_mod(modAliasForm);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        long last_login_time = verifyUser.getLast_login_time();
        //保存登录时间
        UserEntity userEntity = new UserEntity();
        userEntity.setUser_id(verifyUser.getUser_id());
        userEntity.setLast_login_time(System.currentTimeMillis());
        userService.updateUserLoginTime(userEntity);
        //保存登录记录
        LoginRecord loginRecord = new LoginRecord();
        loginRecord.setCompany_id(verifyUser.getCompany_id());
        loginRecord.setLogin_time(System.currentTimeMillis());
        loginRecord.setUser_id(verifyUser.getUser_id());
        loginRecord.setLogin_ip(form.getIp());
        loginRecordService.save(loginRecord);
        //登录成功拼装缓存数据 删除游客token
        UserCache userCache = new UserCache();
        //后台数据缓存
        BrokerVO brokerVO = new BrokerVO();
        UserTokenUtil.setBGBrokerVO(brokerVO, form);
        brokerVO.setCompany_id(verifyUser.getCompany_id());
        brokerVO.setSendercomp_id(verifyUser.getSendercomp_id());
        brokerVO.setLast_login_time(last_login_time);
        userCache.setBrokerVO(brokerVO);
        userCache.setAccess_token(form.getAuthorization_token());
        UserType user_type=UserType.CUSTOMER;
        if("1".equals(userT2InfoBack.getUser_type())){
            user_type = UserType.ADMIN;
        }else if("2".equals(userT2InfoBack.getUser_type())){
            user_type = UserType.LEADER;
        }
        switch (user_type){
            case CUSTOMER:{
                Customer customer = customerService.getCustomer(new Customer(verifyUser.getAccounts_id()));
                //保存极光推送信息
                if(!StringUtil.isEmpty(form.getRegistration_id())) {
                    RegisterForm regForm = new RegisterForm();
                    regForm.setRegistration_id(form.getRegistration_id());
                    UserVO userVO = new UserVO();
                    userVO.setUser_id(verifyUser.getUser_id());
                    regForm.setUser(userVO);
                    regForm.setCompany_id(form.getCompany_id());
                    regForm.setSendercomp_id(form.getCompany_id());
                    regForm.setTerminal_type(form.getTerminal_type());
                    try {
                        pushService.registrationIdMgr(regForm);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
                if (null != customer) {
                    CustomerBackVo customerBackVo = JSON.parseObject(JSON.toJSONString(customer),CustomerBackVo.class);
                    initParentField(customerBackVo, verifyUser);
                    customerBackVo.setAlias_name(userT2InfoBack.getAlias_name());
                    customerBackVo.setAvatar(userT2InfoBack.getAvatar());
                    customerBackVo.setCity_name(userT2InfoBack.getCity_name());
                    customerBackVo.setProvince_name(userT2InfoBack.getProvince_name());
                    userCache.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
                    customerBackVo.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
                    customerBackVo.setUser_key(verifyUser.getUser_key());
                    userCache.getBrokerVO().setUser(customerBackVo);
                }else {
                    return VOUtil.genErrorResult(CUSTOMER_INFO_NOT_EXIST, UserLoginBack.class);
                }
            }
            break;
            case LEADER:{
                Leader leader = leaderService.getLeader(new Leader(verifyUser.getAccounts_id()));
                if (null != leader) {
                    LeaderInfoVo leaderInfoVo =JSON.parseObject(JSON.toJSONString(leader),LeaderInfoVo.class);
                    initParentField(leaderInfoVo, verifyUser);
                    leaderInfoVo.setAlias_name(userT2InfoBack.getAlias_name());
                    leaderInfoVo.setAvatar(userT2InfoBack.getAvatar());
                    leaderInfoVo.setCity_name(userT2InfoBack.getCity_name());
                    leaderInfoVo.setProvince_name(userT2InfoBack.getProvince_name());
                    userCache.setUser_type(String.valueOf(UserType.LEADER.getVal()));
                    leaderInfoVo.setUser_type(String.valueOf(UserType.LEADER.getVal()));
                    leaderInfoVo.setUser_key(verifyUser.getUser_key());
                    userCache.getBrokerVO().setUser(leaderInfoVo);
                }else {
                    return VOUtil.genErrorResult(LEADER_INFO_NOT_EXIST, UserLoginBack.class);
                }
            }
            break;
            case ADMIN:
                break;
            default:
                break;
        }
        String user_token = UserTokenUtil.addUserToken(userCache);
        UserLoginBack userLoginBack = new UserLoginBack();
        userLoginBack.setUser_token(user_token);
        return VOUtil.setSuccessResult(userLoginBack);
    }

    /**
     * 后台接口查询投顾用户是否已通过认证
     * */
    private InterestDetailVo leaderIsPassed(UserLoginForm form, Long user_id){
        InterestDetailForm interestDetailForm = new InterestDetailForm();
        interestDetailForm.setOp_branch_no(form.getOp_branch_no());
        interestDetailForm.setOp_entrust_way(form.getOp_entrust_way());
        interestDetailForm.setOp_station(form.getOp_station());
        interestDetailForm.setBranch_no(form.getBranch_no());
        interestDetailForm.setUser_id(String.valueOf(user_id));
        interestDetailForm.setSendercomp_id(form.getSendercomp_id());
        interestDetailForm.setUser_token(form.getUser_token());
        interestDetailForm.setNeed_user_id(form.getNeed_user_id());
        //增加一个临时校验Token
        String tmp_token = UserTokenUtil.addTempUserToken(form.getCompany_id(), form.getSendercomp_id());
        interestDetailForm.setUser_token(tmp_token);
        InterestDetailVo interestDetailVo = lightinvestingService.func_interest_detail_query(interestDetailForm);
        //临时token使用后删除
        UserTokenUtil.deleteUserToken(tmp_token);
        //后台返回领投type为6 领投type等于5
        if (interestDetailVo == null || (!interestDetailVo.getUser_type().equals("6"))){
            return null;
        }
        return interestDetailVo;
    }


    /**
     * 拼装用户缓存
     * */
    public  <T extends UserVO> void initParentField(T user, UserEntity userEntity){
        user.setSendercomp_id(userEntity.getSendercomp_id());
        user.setCompany_id(userEntity.getCompany_id());
        user.setMobile(userEntity.getMobile());
        user.setAlias_name(userEntity.getAlias_name());
        user.setUser_id(userEntity.getUser_id());
        user.setUser_name(userEntity.getUser_name());
        user.setSalt(userEntity.getSalt());
        user.setYunxin_accid(userEntity.getYunxin_accid());
        user.setYunxin_token(userEntity.getYunxin_token());
        user.setQq_open_id(userEntity.getQq_open_id());
        user.setWeibo_id(userEntity.getWeibo_id());
        user.setCif_id(userEntity.getCif_id());
        user.setWx_public_account(userEntity.getWx_public_account());
        user.setUser_type(userEntity.getUser_type());
        user.setAccounts_id(userEntity.getAccounts_id());
        user.setCompany_id(userEntity.getCompany_id());
        user.setAlias_name(userEntity.getAlias_name());
        user.setAvatar(userEntity.getAvatar());
        user.setMobile(userEntity.getMobile());
    }

    /**
     *  用户密码重置
     * */
    @Override
    public HSBCPSBackVO funcUserPasswordRest(UserPasswordRestForm form) {
        String mobile_tel = form.getMobile_tel();
        String company_key = form.getCompany_id();
        String sendercomp_id = form.getSendercomp_id();
        if (form.getUser_type().equals(String .valueOf(UserType.CUSTOMER.getVal()))){
            if (form.getUser_token().equals("")){
                return VOUtil.genErrorResult(NOT_LOGGED, HSBCPSBackVO.class);
            }
        }
        String verify_token = VerifyCodeTokenUtil.getVerifyCodeToken(mobile_tel + company_key + sendercomp_id,
                VerifySource.RESET_PASSWORD);
        if (ConfigValues.getVerifyCodeSuperSwitch()){
            if (!form.getAuth_check_code().equals(ConfigValues.getVerifyCodeSuperValue())){
                return VOUtil.genErrorResult(VERIFY_CODE_WRONG, UserLoginBack.class);
            }
        }else{
            if (!VerifyCodeTokenUtil.isRight(verify_token, form.getAuth_check_code())){
                return VOUtil.genErrorResult(VERIFY_CODE_WRONG, HSBCPSBackVO.class);
            }
            if (VerifyCodeTokenUtil.isTimeOut(verify_token)){
                return VOUtil.genErrorResultVo(HSBCPSErrorCodes.CommonErr.VERIFY_CODE_TIMEOUT);
            }
        }

        PasswordResetForm passwordResetForm = new PasswordResetForm();
        passwordResetForm.setLogin_account(form.getMobile_tel());
        if(form.getUser_type().equals("100")){
            passwordResetForm.setUser_type("3");
        }else if(form.getUser_type().equals("101")){
            passwordResetForm.setUser_type("2");
        }
        passwordResetForm.setTenant_id(form.getCompany_id());
        passwordResetForm.setAuth_code(form.getAuth_check_code());
        passwordResetForm.setAuth_password(MD5Util.encrypt(form.getNew_password()));
        PasswordResetVo passwordResetVo = userCenterService.func_password_reset(passwordResetForm);
        if(!"0".equals(passwordResetVo.getError_no())) {
            return VOUtil.genErrorResult(passwordResetVo.getError_no(),passwordResetVo.getError_info(),HSBCPSBackVO.class);
        }
        return VOUtil.genSuccessBackVo();
    }

    /**
     * 用户登出
     * */
    @Override
    public HSBCPSBackVO funcUserLogOut(UserLogoutForm form) {
        UserCache userCache = UserTokenUtil.queryUserToken(form.getUser_token());
        LogoutForm logoutForm= new LogoutForm();
        logoutForm.setUser_token(userCache.getAccess_token());
        LogoutVo userT2Back=userCenterService.func_logout(logoutForm);
        if(!"0".equals(userT2Back.getError_no())) {
            return VOUtil.genErrorResult(userT2Back.getError_no(),userT2Back.getError_info(),HSBCPSBackVO.class);
        }
        UserTokenUtil.deleteUserToken(form.getUser_token());
        return VOUtil.genSuccessBackVo();
    }


    /**
     * 用户密码修改
     * */
    @Override
    public HSBCPSBackVO funcUserPasswordChange(UserPasswordUpdateForm form) {
        UserCache userCache = UserTokenUtil.queryUserToken(form.getUser_token());
        UserUpdatePasswordForm userUpdatePasswordForm = new UserUpdatePasswordForm();
        userUpdatePasswordForm.setUser_token(userCache.getAccess_token());
        userUpdatePasswordForm.setAuth_password(MD5Util.encrypt(form.getNew_password()));
        userUpdatePasswordForm.setOld_password(MD5Util.encrypt(form.getPassword()));
        UserUpdatePasswordVo  userT2Back = userCenterService.func_user_update_password(userUpdatePasswordForm);
        if(!"0".equals(userT2Back.getError_no())) {
            return VOUtil.genErrorResult(userT2Back.getError_no(),userT2Back.getError_info(), HSBCPSBackVO.class);
        }
        return VOUtil.genSuccessBackVo();
    }

    /**
     * 用户昵称修改
     * */
    @Transactional
    @Override
    public HSBCPSBackVO funcUserAliasNameChange(UserAliasNameForm form) {
        //敏感词过滤
        if (StringReplacer.hasSensitiveWord(form.getAlias_name(), form.getCompany_id())){
            return VOUtil.genErrorResult(ALIAS_NAME_CONTAIN_SENSITIVE_WORD, HSBCPSBackVO.class);
        }
        UserEntity userEntity = new UserEntity();
        userEntity.setAlias_name(form.getAlias_name());
        userEntity.setUser_id(form.getUser().getUser_id());
        userService.update(userEntity);
        UserCache userCache = UserTokenUtil.queryUserToken(form.getUser_token());
        com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.ifs.UserUpdateForm
                userUpdateForm  = new com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.ifs.UserUpdateForm();
        userUpdateForm.setAlias_name(form.getAlias_name());
        userUpdateForm.setUser_token(userCache.getAccess_token());
        UserUpdateVo  userT2Back = userCenterService.func_user_update(userUpdateForm);
        if(!"0".equals(userT2Back.getError_no())) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return VOUtil.genErrorResult(userT2Back.getError_no(),userT2Back.getError_info(), HSBCPSBackVO.class);
//            throw new RuntimeException(userT2Back.getError_no() + "|" + userT2Back.getError_info());
        }
        UserTokenUtil.updateByUpdateKey(form.getUser_token(), form.getAlias_name(), UserCacheFreshType.UPDATE_ALIAS);
        ModAliasForm modAliasForm = new ModAliasForm();
        modAliasForm.setAlias_name(form.getAlias_name());
        modAliasForm.setUser_id(String.valueOf(form.getUser().getUser_id()));
        modAliasForm.setSendercomp_id(form.getSendercomp_id());
        modAliasForm.setUser_token(form.getUser_token());
        modAliasForm.setNeed_user_id(form.getNeed_user_id());
        ModAliasVo modAliasVo = lightinvestingService.func_alias_mod(modAliasForm);
        if (modAliasVo.getSerial_no() == null){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return VOUtil.genBGErrorResult(modAliasVo.getError_no(),
                    modAliasVo.getExt_error_info(), HSBCPSBackVO.class);
//            throw new RuntimeException(userT2Back.getError_no() + "|" + userT2Back.getError_info());
        }
        return VOUtil.genSuccessBackVo();
    }

    /**
     * 用户头像修改
     * */
    @Override
    @Transactional
    public HSBCPSBackVO funcUserHeadpicChange(UserAvatarForm form) {
        UserEntity userEntity = new UserEntity();
        userEntity.setAvatar(form.getFile_path());
        userEntity.setUser_id(form.getUser().getUser_id());
        userService.update(userEntity);
        UserCache userCache = UserTokenUtil.queryUserToken(form.getUser_token());
        com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.ifs.UserUpdateForm
                userUpdateForm  = new com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.ifs.UserUpdateForm();
        userUpdateForm.setAvatar(form.getFile_path());
        userUpdateForm.setUser_token(userCache.getAccess_token());
        UserUpdateVo  userT2Back = userCenterService.func_user_update(userUpdateForm);
        if(!"0".equals(userT2Back.getError_no())) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return VOUtil.genErrorResult(userT2Back.getError_no(),userT2Back.getError_info(), HSBCPSBackVO.class);
//            throw new RuntimeException(userT2Back.getError_no() + "|" + userT2Back.getError_info());
        }
        UserTokenUtil.updateByUpdateKey(form.getUser_token(), form.getFile_path(), UserCacheFreshType.UPDATE_AVATAR);
        return VOUtil.genSuccessBackVo();
    }

    /**
     * 用户个人信息获取
     * */
    @Override
    public UserInfoBack funcUserInfoQuery(UserInfoQryForm form) {
        UserCache userCache = UserTokenUtil.queryUserToken(form.getUser_token());
        BrokerVO brokerVO = userCache.getBrokerVO();
        UserVO userVO = brokerVO.getUser();
        UserInfoBack userInfoBack = new UserInfoBack();
//        UserEntity userEntity = userService.getUserEntity(new UserEntity(form.getUser().getUser_id()));
        userInfoBack.setUser_id(userVO.getUser_id());
        userInfoBack.setMobile_tel(userVO.getMobile());
        userInfoBack.setAlias_name(userVO.getAlias_name());
        userInfoBack.setHeadpic_path(userVO.getAvatar());
        userInfoBack.setAvatar_base64(userVO.getAvatar());
        userInfoBack.setLast_login_time(brokerVO.getLast_login_time());
        return VOUtil.setSuccessResult(userInfoBack);
    }

    /**
     * 游客身份登录
     * */
    @Override
    public UserLoginBack funcVisitorLogin(VisitorLoginForm form) {
        UserCache userCache = new UserCache();
        BrokerVO brokerVO = new BrokerVO();
        brokerVO.setCompany_id(form.getCompany_id());
        brokerVO.setSendercomp_id(form.getSendercomp_id());
        brokerVO.setOp_branch_no(form.getOp_branch_no());
        brokerVO.setBranch_no(form.getBranch_no());
        brokerVO.setOperator_no(form.getOperator_no());
        brokerVO.setOp_entrust_way(form.getOp_entrust_way());
        brokerVO.setOp_station(form.getOp_station());
        brokerVO.setTerminal_type(form.getTerminal_type());
        userCache.setBrokerVO(brokerVO);
        userCache.setUser_type(String.valueOf(UserType.VISITOR.getVal()));
        String user_token = UserTokenUtil.addVisitorToken(userCache);
        UserLoginBack userLoginBack = new UserLoginBack();
        userLoginBack.setUser_token(user_token);
        return VOUtil.setSuccessResult(userLoginBack);
    }


    /**
     * 在db与缓存中刷新用户密码
     * */
    private void updatePasswordInCacheAndDB(String user_token, String password){
        String new_password = MD5Util.encrypt(password);
        //fresh db
        userService.updatePassword(new UserEntity(
                UserTokenUtil.queryUserToken(user_token).getBrokerVO().getUser().getUser_id()
                , new_password));
        //fresh cache 缓存不存密码
//        UserTokenUtil.updateByUpdateKey(user_token, new_password, UserCacheFreshType.UPDATE_PASSWORD);
    }
    @Transactional
    public UserLoginBack funcXiNanLogin(XiNanUserLoginForm form){

        String temp_token = form.getTemp_token();
        String user_name = form.getUser_name();
        Long user_id = null;
        String login_way = form.getLogin_way();
        String headimgurl = form.getHeadimgurl();
        String alias_name = "";
        if (form.getNickname()!=null && !StringUtil.isBlank(form.getNickname())){
            alias_name = form.getNickname();
        } else {
            alias_name = user_name;
        }

        if (login_way.equals(String.valueOf(LoginAwayType.XINAN.getVal()))){
            return VOUtil.genErrorResult(USER_LOGIN_AWAY_ERROE, UserLoginBack.class);
        }
        //检验用户是否在思迪账户注册
        if (!accountIsExist(user_name,temp_token)){
            return VOUtil.genErrorResult(USER_NOT_REG_IN_XINAN, UserLoginBack.class);
        }

        //检验用户是否已经存在
        UserEntity verifyUser = userService.userLoginVerify(new UserEntity(user_name,
                form.getUser_type(), form.getSendercomp_id(), form.getCompany_id()));

        //本地注册--itn--本地--后台
        if(null == verifyUser ){

            CheckRegisterForm checkRegisterForm = new CheckRegisterForm();
            checkRegisterForm.setTenant_id(form.getCompany_id());
            checkRegisterForm.setUser_type("3");
            checkRegisterForm.setLogin_account(user_name);

            CheckRegisterVo checkRegisterVo = userCenterService.func_check_register(checkRegisterForm);
            if (checkRegisterVo !=null && "0".equals(checkRegisterVo.getIs_register())){
                //用户中心未注册进行注册
                com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.ifs.RegisterForm userRegisterForm =
                        new com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.ifs.RegisterForm();
                userRegisterForm.setLogin_account(user_name);
                userRegisterForm.setAuth_password(MD5Util.encrypt(UUID.randomUUID().toString()));
                userRegisterForm.setUser_type("3");
                userRegisterForm.setTenant_id(form.getCompany_id());
                userRegisterForm.setAlias_name(alias_name);
                userRegisterForm.setAvatar(headimgurl);
                userRegisterForm.setRegister_flag("2");
                userRegisterForm.setMobile(user_name);
                RegisterVo userT2RegBack = userCenterService.func_register(userRegisterForm);
                if(!"0".equals(userT2RegBack.getError_no())){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return VOUtil.genErrorResult(userT2RegBack.getError_no(),userT2RegBack.getError_info(), UserLoginBack.class);
//                    throw new RuntimeException(userT2RegBack.getError_no() + "|" + userT2RegBack.getError_info());
                }
                user_id = Long.valueOf(userT2RegBack.getUser_id());
            }

            String mobile_tel = user_name;
            String sendercomp_id = form.getSendercomp_id();
            String user_type = String.valueOf(UserType.CUSTOMER.getVal());
            String company_id = form.getCompany_id();
            Customer new_customer =new Customer(alias_name,mobile_tel,
                    System.currentTimeMillis(), company_id);
            customerService.addCustomer(new_customer);
            //注册到ITN

            AuthuserRegbindVo authuserRegbindVo = new AuthuserRegbindVo();
            try {
                authuserRegbindVo = register2ITN(mobile_tel,sendercomp_id,form.getUser_token());
            }catch (Exception e){
                //成功与否不要影响注册流程
                e.printStackTrace();
            }
            if (authuserRegbindVo == null || authuserRegbindVo.getUser_id() == null){
                authuserRegbindVo.setUser_id("0");
            }
            //刷新user信息
            long customer_id = new_customer.getCustomer_id();
            //更新user表
            String user_key = String.valueOf(System.nanoTime());
            UserEntity userEntity = new UserEntity();
            userEntity.setUser_id(user_id);
            userEntity.setCompany_id(form.getCompany_id());
            userEntity.setSendercomp_id(form.getSendercomp_id());
            userEntity.setPassword(MD5Util.encrypt(form.getPassword()));
            userEntity.setUser_name(mobile_tel);
            userEntity.setAccounts_id(customer_id);
            userEntity.setUser_key(user_key);
            userEntity.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
            userEntity.setMobile(mobile_tel);
            userEntity.setAlias_name(alias_name);
            userEntity.setAvatar(headimgurl);
            userEntity.setUser_status(String.valueOf(UserStatus.NORMAL.getVal()));
            userEntity.setOpen_id(form.getOpen_id());
            userService.addUser(userEntity);

            //customer数据组装
            UserCache userCache = new UserCache();
            BrokerVO brokerVO = new BrokerVO();
            CustomerBackVo customerBackVo = new CustomerBackVo();
            customerBackVo.setCustomer_id(userEntity.getAccounts_id());
            UserTokenUtil.setBGBrokerVO(brokerVO, form);
            initParentField(customerBackVo, userEntity);
            brokerVO.setUser(customerBackVo);
            form.setUser_key(String.valueOf(userEntity.getUser_id()));
            UserTokenUtil.setBGBrokerVO(brokerVO, form);
            userCache.setBrokerVO(brokerVO);
            UserLoginBack userLoginBack = new UserLoginBack();
            String user_token = UserTokenUtil.addUserToken(userCache);
            //本地注册成功后发送数据到后台注册
            RegBackVo backVo =register2Backend(alias_name,String.valueOf(userEntity.getUser_id()),mobile_tel,sendercomp_id,user_token);
            if (backVo.getSerial_no() == null){
                UserTokenUtil.deleteUserToken(user_token);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return VOUtil.genErrorResult(backVo.getError_no(),backVo.getError_info(),UserLoginBack.class);
//                throw new RuntimeException(backVo.getError_no() + "|" + backVo.getError_info());
            }
            userLoginBack.setUser_token(user_token);
            //删除游客token
            UserTokenUtil.deleteUserToken(form.getUser_token());
            userLoginBack.setUser_id(userEntity.getUser_id());
            return VOUtil.setSuccessResult(userLoginBack);
        }

        //校验用户状态是否为正常
        if (!verifyUser.getUser_status().equals(String.valueOf(UserStatus.NORMAL.getVal()))){
            return VOUtil.genErrorResult(USER_STATUS_DISABLE, UserLoginBack.class);
        }
        //已经注册过的用户登录
        UserCache userCache = new UserCache();
        BrokerVO brokerVO = new BrokerVO();
        UserEntity user = new UserEntity();
        CustomerBackVo customerBackVo = new CustomerBackVo();
        customerBackVo.setCustomer_id(verifyUser.getAccounts_id());
        UserTokenUtil.setBGBrokerVO(brokerVO, form);
        initParentField(customerBackVo, verifyUser);
        brokerVO.setUser(customerBackVo);
        form.setUser_key(String.valueOf(verifyUser.getUser_id()));
        userCache.setBrokerVO(brokerVO);
        String user_token = UserTokenUtil.addUserToken(userCache);
        UserLoginBack userLoginBack = new UserLoginBack();
        userLoginBack.setUser_token(user_token);
        userLoginBack.setUser_id(customerBackVo.getUser_id());
        //更新open_id
        verifyUser.setOpen_id(form.getOpen_id());
        userService.updateOpenId(verifyUser);
        return VOUtil.setSuccessResult(userLoginBack);
    }

    @Override
    public UserBasicInfoList funcUserBasicInfoListQry(UserBasicInfoListQryForm form) {
        UserBasicInfoList userBasicInfoList = new UserBasicInfoList();
        UsersQueryVo usersQueryVo = userCenterService.func_users_query(form.getUser_ids());
        List<UserBasicInfoData> userBasicInfoDataList = new ArrayList<>();
        for (UserEntityVO result :usersQueryVo.getData_list()) {
            UserBasicInfoData userBasicInfoData = new UserBasicInfoData();
            userBasicInfoData.setUser_id(result.getUser_id());
            userBasicInfoData.setAvatar(result.getAvatar());
            userBasicInfoData.setAlias_name(result.getAlias_name());
            userBasicInfoDataList.add(userBasicInfoData);
        }
        userBasicInfoList.setData_list(userBasicInfoDataList);
        return VOUtil.setSuccessResult(userBasicInfoList);
    }

    //注册到ITN
    private AuthuserRegbindVo register2ITN(String mobile_tel,String sendercompany_id,
                                           String user_token){

        AuthuserRegbindForm authuserRegbindForm = new AuthuserRegbindForm();
        authuserRegbindForm.setBusinsys_no(Long.valueOf(1001));
        authuserRegbindForm.setSendercomp_id(sendercompany_id);
        authuserRegbindForm.setMobile_tel(mobile_tel);
        authuserRegbindForm.setUser_token(user_token);
        AuthuserRegbindVo authuserRegbindVo = lightinvestingService.func_authuser_regbind(authuserRegbindForm);
        return authuserRegbindVo;
    }

    private RegBackVo register2Backend(String alias_name,String user_id,
                                       String mobile_tel,String sendercompany_id,
                                       String user_token){
        RegForm regForm = new RegForm();
        regForm.setAlias_name(alias_name);
        regForm.setMobile_tel(mobile_tel);
        regForm.setNeed_user_id("1");
        regForm.setUser_id(String.valueOf(user_id));
        regForm.setSendercomp_id(sendercompany_id);
        regForm.setUser_token(user_token);
        RegBackVo backVo = lightinvestingService.func_register_authuser(regForm);
        return backVo;
    }

    private static boolean accountIsExist(String account,String temp_token){
        String url = ConfigUtil.get("account_service_url");//"http://113.204.68.206:8081/account/servlet/call";
//        String url = "http://113.204.68.206:8081/account/servlet/call";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("temp_token",temp_token);
        Map paramMap = new HashMap<>();
        paramMap.put("bizcode","uums_get_uid");
        paramMap.put("merchant_id",ConfigUtil.get("merchant_id"));
//        paramMap.put("merchant_id","ltb");//"ltb"
        byte[] data = Base64Utils.encode(jsonObject.toJSONString().getBytes());
        paramMap.put("data",new String(data));
        Map signMap = new TreeMap<>(paramMap);
        signMap.put("signKey",ConfigUtil.get("MD5key"));
//        signMap.put("signKey","4db7b064f5455b890e1deadc5ef90e6e");

        String a = MD5Util.dictSort(signMap);
        if (a !=null && a.length()>1)
            a = a.substring(0,a.length()-1);
        paramMap.put("sign",MD5Util.encrypt(a));
        String result = HttpUtil.doPost(url,paramMap);
        JSONObject json = JSON.parseObject(result);
        //对结果集进行判断
        if (json!=null && json.get("error_no").equals("0")&&json.get("user_info")!=null) {
            List<Map> list = (List<Map>) json.get("user_info");
            if (list==null || list.size()==0){
                return false;
            }
            if (list.get(0).get("mobile").equals(account)) {
                return true;
            } else {
                return false;
            }
        }else {
            return false;
        }
    }


    public InviteInfoBack func_get_invite_info(InviteinfoForm form){
        UserEntity userEntity = userService.getUserEntity(new UserEntity(form.getUser().getUser_id()));
        InviteInfoBack inviteInfoBack = new InviteInfoBack();
        inviteInfoBack.setInvite_num(userEntity.getInvite_num());
        inviteInfoBack.setInvite_code(userEntity.getInvite_code());
        inviteInfoBack.setUser_id(userEntity.getUser_id());
        int phone_charge=0;
        int invite_num=userEntity.getInvite_num();
        phone_charge+=(invite_num/10)*25+((invite_num%10)/5)*10+(((invite_num%10)%5)/3)*5;
        if(phone_charge>100){
            phone_charge=100;
        }
        inviteInfoBack.setPhone_charge(phone_charge);
        return VOUtil.setSuccessResult(inviteInfoBack);
    }



    public HSBCPSBackVO func_user_open_app(UserOpenAppForm form){
        String access_token = form.getUser_token();
        //游客token不作处理
        if (access_token.indexOf("visitor") != -1){
            return VOUtil.genErrorResult(BasicErrorCodes.INVALID_ERROR,HSBCPSBackVO.class);
        }
        UserCache identity = UserTokenUtil.queryUserToken(access_token);
        //token失效
        if (null == identity) {
            //游客超时
            return VOUtil.genErrorResult(BasicErrorCodes.INVALID_ERROR,HSBCPSBackVO.class);
        }
        return VOUtil.genSuccessBackVo();
    }


    public RongYunTokenBack funcRongYunToken(RongYunTokenQueryForm form){
        try {

            String user_id = String.valueOf(form.getUser().getUser_id());
            String name =  form.getUser().getAlias_name();
            String portraitUri = form.getUser().getAvatar()==null?"":form.getUser().getAvatar();

            String nonce = String.valueOf(Math.random() * 1000000);
            String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
            String appsecret = ConfigUtil.get("rongyun_appsecret");
            StringBuilder toSign = new StringBuilder(appsecret).append(nonce).append(timestamp);

            StringBuilder sb = new StringBuilder();
            sb.append("&userId=").append(URLEncoder.encode(user_id, "utf-8"));
            sb.append("&name=").append(URLEncoder.encode(name, "utf-8"));
            sb.append("&portraitUri=").append(URLEncoder.encode(portraitUri, "utf-8"));
            String body = sb.toString();
            if (body.indexOf("&") == 0) {
                body = body.substring(1, body.length());
            }

            URL url = new URL("http://api.cn.ronghub.com/user/getToken.json");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setInstanceFollowRedirects(true);
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);

            conn.setRequestProperty("App-Key", ConfigUtil.get("rongyun_appkey"));
            conn.setRequestProperty("Nonce", nonce);
            conn.setRequestProperty("Timestamp", timestamp);
            conn.setRequestProperty("signature",SHA1Util.getSha1(toSign.toString()));
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());
            out.write(body.getBytes("utf-8"));
            out.flush();
            out.close();
            InputStream input = null;
            if (conn.getResponseCode() == 200) {
                input = conn.getInputStream();
            } else {
                input = conn.getErrorStream();
            }
            String result = new String(SSLHttpUtil.readInputStream(input), "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(result);

            RongYunTokenBack rongYunTokenBack = new RongYunTokenBack();
            rongYunTokenBack.setToken(jsonObject.getString("token"));
            rongYunTokenBack.setUserId(jsonObject.getString("userId"));
            return VOUtil.setSuccessResult(rongYunTokenBack);
        }catch (Exception ex) {
            ex.printStackTrace();
            return VOUtil.genErrorResult("1",RongYunTokenBack.class);
        }

    }
}
